<template>
  <div class="settings-container">
    <el-row :gutter="20">
      <!-- 个人设置 -->
      <el-col :xs="24" :sm="24" :md="16">
        <el-card class="settings-card">
          <template #header>
            <div class="card-header">
              <span>个人设置</span>
              <el-button type="primary" @click="handleSave" :loading="loading">
                保存修改
              </el-button>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="settingsForm"
            :rules="rules"
            label-width="120px"
          >
            <!-- 基本设置 -->
            <h3 class="settings-section">基本设置</h3>
            <el-form-item label="语言" prop="language">
              <el-radio-group v-model="settingsForm.language">
                <el-radio-button value="zh-CN">中文</el-radio-button>
                <el-radio-button value="en-US">English</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="主题模式" prop="theme">
              <el-radio-group v-model="settingsForm.theme">
                <el-radio-button value="light">浅色</el-radio-button>
                <el-radio-button value="dark">深色</el-radio-button>
                <el-radio-button value="system">跟随系统</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <!-- 隐私设置 -->
            <h3 class="settings-section">隐私设置</h3>
            <el-form-item label="个人资料可见性" prop="profileVisibility">
              <el-radio-group v-model="settingsForm.profileVisibility">
                <el-radio-button value="public">公开</el-radio-button>
                <el-radio-button value="private">仅自己可见</el-radio-button>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="数据分享" prop="dataSharing">
              <el-switch
                v-model="settingsForm.dataSharing"
                active-text="允许分享匿名数据用于改进服务"
              />
            </el-form-item>

            <!-- 通知设置 -->
            <h3 class="settings-section">通知设置</h3>
            <el-form-item label="邮件通知">
              <el-checkbox-group v-model="settingsForm.emailNotifications">
                <el-checkbox label="goals">目标提醒</el-checkbox>
                <el-checkbox label="reports">周报/月报</el-checkbox>
                <el-checkbox label="tips">营养建议</el-checkbox>
                <el-checkbox label="news">新功能通知</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="应用内通知">
              <el-checkbox-group v-model="settingsForm.appNotifications">
                <el-checkbox label="meals">膳食提醒</el-checkbox>
                <el-checkbox label="water">饮水提醒</el-checkbox>
                <el-checkbox label="weight">体重记录提醒</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="提醒时间">
              <el-time-picker
                v-model="settingsForm.reminderTime"
                format="HH:mm"
                placeholder="选择提醒时间"
              />
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 数据管理 -->
      <el-col :xs="24" :sm="24" :md="8">
        <el-card class="settings-card">
          <template #header>
            <div class="card-header">
              <span>数据管理</span>
            </div>
          </template>

          <div class="data-management">
            <div class="data-item">
              <h4>导出数据</h4>
              <p>导出您的所有数据，包括个人信息、膳食记录和目标设置等。</p>
              <el-button type="primary" plain @click="handleExportData">
                导出数据
              </el-button>
            </div>

            <el-divider />

            <div class="data-item">
              <h4>清除缓存</h4>
              <p>清除本地缓存数据，这不会影响您的账号数据。</p>
              <el-button plain @click="handleClearCache">
                清除缓存
              </el-button>
            </div>

            <el-divider />

            <div class="data-item danger-zone">
              <h4>账号注销</h4>
              <p>永久删除您的账号和所有相关数据，此操作不可撤销。</p>
              <el-button type="danger" plain @click="handleDeleteAccount">
                注销账号
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useStore()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

// 设置表单
const settingsForm = reactive({
  language: 'zh-CN',
  theme: 'light',
  profileVisibility: 'private',
  dataSharing: true,
  emailNotifications: ['goals', 'reports'],
  appNotifications: ['meals', 'water', 'weight'],
  reminderTime: new Date(2000, 0, 1, 9, 0)
})

// 表单验证规则
const rules = {
  language: [
    { required: true, message: '请选择语言', trigger: 'change' }
  ],
  theme: [
    { required: true, message: '请选择主题模式', trigger: 'change' }
  ],
  profileVisibility: [
    { required: true, message: '请选择可见性', trigger: 'change' }
  ]
}

// 初始化设置表单
onMounted(async () => {
  try {
    const res = await store.dispatch('user/getSettings')
    Object.assign(settingsForm, res.data)
  } catch (error) {
    console.error('获取设置失败:', error)
    ElMessage.error('获取设置失败')
  }
})

// 保存设置
const handleSave = () => {
  formRef.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true
        await store.dispatch('user/updateSettings', settingsForm)
        ElMessage.success('设置保存成功')
      } catch (error) {
        console.error('保存设置失败:', error)
        ElMessage.error('保存失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 导出数据
const handleExportData = async () => {
  try {
    const res = await store.dispatch('user/exportData')
    const blob = new Blob([JSON.stringify(res.data, null, 2)], { type: 'application/json' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `diet-data-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出失败')
  }
}

// 清除缓存
const handleClearCache = () => {
  ElMessageBox.confirm(
    '确定要清除本地缓存吗？这不会影响您的账号数据。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    localStorage.clear()
    ElMessage.success('缓存已清除')
    setTimeout(() => {
      window.location.reload()
    }, 1500)
  })
}

// 注销账号
const handleDeleteAccount = () => {
  ElMessageBox.confirm(
    '注销账号将永久删除您的所有数据，此操作不可撤销，是否继续？',
    '警告',
    {
      confirmButtonText: '确认注销',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(async () => {
    try {
      await store.dispatch('user/deleteAccount')
      ElMessage.success('账号已注销')
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } catch (error) {
      console.error('注销账号失败:', error)
      ElMessage.error('注销失败')
    }
  })
}
</script>

<style lang="scss" scoped>
.settings-container {
  padding: 20px;

  .settings-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .settings-section {
      margin: 24px 0 16px;
      padding-bottom: 8px;
      font-size: 16px;
      font-weight: 500;
      color: var(--text-primary);
      border-bottom: 1px solid var(--border-color-lighter);

      &:first-child {
        margin-top: 0;
      }
    }
  }

  .data-management {
    .data-item {
      margin-bottom: 24px;

      h4 {
        margin: 0 0 8px;
        font-size: 16px;
        color: var(--text-primary);
      }

      p {
        margin: 0 0 16px;
        color: var(--text-secondary);
        font-size: 14px;
      }

      &.danger-zone {
        h4 {
          color: var(--danger-color);
        }
      }
    }

    .el-divider {
      margin: 24px 0;
    }
  }
}
</style> 